<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\BaseController;
use App\Models\Honey;
use App\Models\HoneyBalance;
use App\Models\Material;
use App\Models\Order;
use App\Models\User;
use App\Models\Work;
use App\Services\HoneyBalanceService;
use Dingo\Api\Http\Request;

class HoneyController extends BaseController
{
    public $model = Honey::class;

    public function store(Request $request) {
        $this->validate($request, [
           'work_id' => 'required'
        ]);
        $input = $request->input();
        $work = Work::find($input['work_id']);
        if (!$work)
            return $this->failed('work_id 不存在');

        $user = $this->getUser();
        $input['user_id'] = $user->id;
        if ($work->user_id == $user->id)
            return $this->failed('只能赠送他人');

        $count = Honey::hasSendCount($input['user_id'], $input['work_id']);
        if ($count) {
            return $this->failed("一个作品一个用户每天只能送1次蜜糖");
        }
        if ($user->honey_balance < 1)
            return $this->failed("蜜糖余额不足");

        try {
            \DB::beginTransaction();
            $input['date'] = date('Y-m-d');
            $info = Honey::create($input);
            $amount = 1;
            HoneyBalanceService::store($work->user_id, $amount, HoneyBalance::TYPE_SEND_IN, $work->id, false);
            HoneyBalanceService::store($user->id, -$amount, HoneyBalance::TYPE_SEND_OUT, $work->id, false);
            $work->honey_num = $work->honey_num + 1;
            $work->save();
            \DB::commit();
            $id = $info->id;
            return $this->success($id);
        }catch (\Exception $e) {
            \DB::rollBack();
            return $this->failed("赠送失败");
        }
    }

    public function flow(Request $request) {
        $user_id = $this->getUserId();
        $list = HoneyBalance::where('user_id', $user_id)->orderBy("id", "desc")
            ->paginate(\request('per_page', 20));
        foreach ($list as &$item) {
            $item->entity = null;
            if (in_array($item->type, [HoneyBalance::TYPE_CONSUME, HoneyBalance::TYPE_EARN])) {
                $order = Order::find($item->entity_id);
                if ($order->entity_type == Order::ENTITY_MATERIAL) {
                    $item->entity = Material::where('id', $order->entity_id)->first(['title', 'id']);
                }
            }
        }
        return $this->paginate($list);
    }

    public function detail() {
        $user = $this->getUser();
        $data['honey_balance'] = $user->honey_balance;
        $data['user_reg'] = true;
        $data['audit_status'] = $user->audit_status;
        $data['profile'] = false;
        if ($user->avatar_url && $user->nickname && $user->city && $user->desc && $user->skill && $user->mobile) {
            $data['profile'] = true;
        }
        return $this->success($data);
    }
}

